package org.pjlib.common;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.widget.ImageView;

import androidx.annotation.DrawableRes;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.Transformation;
import com.bumptech.glide.request.RequestOptions;
import org.pjlib.BaseApp;
import org.pjlib.R;
import org.pjlib.net.HttpUtils;

/**
 * Created by ws on 2019/04/04.
 */
public class ImgUtils {
    public static void Glide(ImageView iv, Object res) {
        Glide(iv, res, getOption(R.drawable.img_error, 0));
    }
    public static void Glide(ImageView iv, Object res, Transformation<Bitmap> transformation){
        RequestOptions options= getOption(R.drawable.img_error, 0);
        options.transform(transformation);
        Glide(iv,res,options);
    }
    public static String getPicUrl(String url){
        if(!url.contains(":") && !url.contains("storage") ){
            url= HttpUtils.getBaseUrl()+url;
            return url;
        }
        return url;
    }
    public static void Glide(ImageView iv, Object res, RequestOptions options) {
        if(res instanceof String){
            String url= (String) res;
            res=getPicUrl(url);
        }
        try {
            if (iv.getContext() instanceof Activity && ((Activity) iv.getContext()).isDestroyed()) {
                Context ctx = BaseApp.getContext();
                if (ctx != null) {
                    Glide.with(ctx).load(res).apply(options).into(iv);
                }
            } else {
                if (iv.getContext() != null && iv.getContext().getApplicationContext() != null) {
                    Glide.with(iv).load(res).apply(options).into(iv);
                }
            }
        }catch (IllegalArgumentException e){

        }


    }

    public static RequestOptions getOption(@DrawableRes int errorId, @DrawableRes int placeId) {
        RequestOptions options = RequestOptions
                .placeholderOf(placeId)
                .error(errorId);
        return options;
    }

}
